"""
认证相关的 API 端点
"""
from fastapi import APIRouter, HTTPException, status
from ....schemas.user import LoginRequest, LoginResponse
from ....schemas.response import BaseResponse, ErrorResponse
from ....crud.user import user_crud
from ....core.exceptions import InvalidCredentialsError

router = APIRouter()


@router.post(
    "/login",
    response_model=BaseResponse[LoginResponse],
    summary="用户登录",
    description="使用工号和密码进行用户登录"
)
async def login(login_data: LoginRequest):
    """用户登录端点"""
    try:
        # 验证用户凭证
        user = await user_crud.authenticate_user(
            job_number=login_data.job_number,
            password=login_data.password
        )
        
        # 获取用户信息和 token
        user_data = user.to_dict_with_token()
        return BaseResponse[LoginResponse](
            code=200,
            message="登录成功",
            data=LoginResponse(**user_data)
        )
        
    except InvalidCredentialsError as e:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail=str(e.detail)
        )
    except Exception as e:
        raise HTTPException(
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
            detail="登录过程中发生错误"
        )